package br.unifacs.mda.plugin.main.popup.actions;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import br.unifacs.mda.plugin.exception.PimGeneratorException;
import br.unifacs.mda.plugin.importation.impl.XMIImporter;
import br.unifacs.mda.plugin.pimgenerator.PimGeneratorContent;
import br.unifacs.mda.plugin.pimgenerator.impl.PimGenerator;
import br.unifacs.mda.plugin.util.Messages;

public class ImportXMIAction implements IObjectActionDelegate {

	private Shell shell;
	private IResource modelsFolder;
	private IProject project;
	private IFile file;

	/**
	 * Constructor for Action1.
	 */
	public ImportXMIAction() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();

		IStructuredSelection sel = (IStructuredSelection) targetPart.getSite()
				.getSelectionProvider().getSelection();
		this.modelsFolder = (IResource) sel.getFirstElement();
		this.project = this.modelsFolder.getProject();
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {
		
		FileDialog fileDialog = new FileDialog(shell);
		fileDialog.setFilterExtensions(new String[] { "*.xml", "*.xmi" });
		fileDialog.setText("Select Model File");
		String inputXmi = fileDialog.open();

		if (inputXmi != null) {
			String fileName = this.modelsFolder.getLocation().toString() + "/"
					+ this.project.getName();
			try {
				this.generatePim(inputXmi, fileName);
				this.modelsFolder.getProject().refreshLocal(
						IResource.DEPTH_INFINITE, null);
				MessageDialog.openInformation(shell, "MDA Plug-in",
						Messages.PIM_GERADO_SUCESSO);
			} catch (PimGeneratorException e) {
				e.printStackTrace();
			} catch (CoreException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
	}

	private void generatePim(String inputXmi, String fileName)
			throws PimGeneratorException, Exception {

		XMIImporter importer = new XMIImporter(inputXmi, false);
		importer.start();
		PimGenerator pimGenerator = new PimGenerator();
		PimGeneratorContent content = new PimGeneratorContent(pimGenerator,
				fileName);
		content.start();

	}
}
